package com.seeyon.apps.kkARPEvent.util;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.collaboration.manager.ColManager;
//import com.seeyon.apps.formToWeb.util.FTPUtil;
//import com.seeyon.apps.formToWeb.util.HttpKit;
//import com.seeyon.apps.formToWeb.util.TransHtmlToPdfUtils;
//import com.seeyon.apps.formToWeb.util.WebDbUtil;

import org.apache.commons.collections.MapUtils;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.client.CookieStore;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.SystemEnvironment;
import com.seeyon.ctp.common.affair.manager.AffairManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.po.affair.CtpAffair;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.json.JSONUtil;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
//import org.zefer.pd4ml.PD4Constants;
//import org.zefer.pd4ml.PD4ML;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.List;

/**
 * 同步插件方法
 *
 * @Title: SyncEasManagerImpl
 */
public class FormToPdf {

	/**
	 * 日志对象
	 */
	private static final Log log = LogFactory.getLog(FormToPdf.class);
	private static FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
	private static ColManager colManager = (ColManager) AppContext.getBean("colManager");
	private static AffairManager affairManager = (AffairManager) AppContext.getBean("affairManager");
	private static OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
	public static final String FORMDATA_TEMP_FOLDER = new StringBuilder(SystemEnvironment.getSystemTempFolder())
			.append(File.separator).append("fromDataTemp").toString();
	private static String formDataTempleteCode = AppContext.getSystemProperty("formToWeb.formDataTempleteCode");
	// --------------------本地地址---------------------------------------
	//private static String OAIP = "http://127.0.0.1";
	//private static String OATOKEN_URL = "http://127.0.0.1/seeyon/rest/token";
	//private static String RESTNAME = "rest";
	//private static String RESTPWD = "d36e2091-1463-4d39-9172-b7b6bc66087c";
    // --------------------本地地址---------------------------------------
	// --------------------测试地址---------------------------------------
	private static final String OAIP = AppContext.getSystemProperty("ARPUrl.IP");
	private static final String OATOKEN_URL = AppContext.getSystemProperty("OAtokeb.TokenUrl");
	private static final String RESTNAME = AppContext.getSystemProperty("OAtokeb.userName");
	private static final String RESTPWD = AppContext.getSystemProperty("OAtokeb.password");
	// --------------------测试地址---------------------------------------
	private static volatile boolean IS_SYNING_HAND = false;
	private static volatile boolean IS_SYNING_AUTO = false;
	public static final String ARCHIVE_TEMP_FOLDER = new StringBuilder(SystemEnvironment.getSystemTempFolder())
			.append(File.separator).append("archiveTemp").toString();
	/**
	 * HTML转换为PDF的一些参数配置
	 */
	protected static int topValue = 20;
	protected static int leftValue = 10;
	protected static int rightValue = 10;
	protected static int bottomValue = 5;
	protected static int userSpaceWidth = 1550;

	// 20200205新增网站推送相关信息配置
	private String ftpUrl = AppContext.getSystemProperty("docToWeb.ftpUrl");
	private String ftpUser = AppContext.getSystemProperty("docToWeb.ftpUser");
	private String ftpPassword = AppContext.getSystemProperty("docToWeb.ftpPassword");
	private String ftpPort = AppContext.getSystemProperty("docToWeb.ftpPort");

	public boolean isSyningHand() {
		return IS_SYNING_HAND;
	}

	public boolean isSyningAuto() {
		return IS_SYNING_AUTO;
	}

	private void setSyningHand(boolean isSyningHand) {
		IS_SYNING_HAND = isSyningHand;
	}

	private void setSyningAuto(boolean syningAuto) {
		IS_SYNING_AUTO = syningAuto;
	}



	/***
	 * cap4转pdf
	 * 
	 * @return
	 * @throws BusinessException
	 */
	public static String cap4FormToPdf(CtpAffair affair, long summaryId) {
		String fileName = "服务器托管申请表";
		String pdfURL = null;
		try {
			pdfURL = "";
			String bodyContent = "";

			V3xOrgMember memberSender = orgManager.getMemberById(affair.getSenderId());
			String loginName = memberSender.getLoginName();
			if (StringUtils.isBlank(loginName)) {
				List<CtpAffair> affairsList = affairManager.getAffairs(affair.getObjectId());
				if (affairsList != null && affairsList.size() > 0) {
					for (CtpAffair ctpAffair : affairsList) {
						V3xOrgMember member = orgManager.getMemberById(ctpAffair.getMemberId());
						if (StringUtils.isNotBlank(member.getLoginName())) {
							loginName = member.getLoginName();
							break;
						}
					}
				}
			}

			Map tokenMap = new HashMap<String,Object>();
			tokenMap.put("loginName", loginName);
			tokenMap.put("password", RESTPWD);
			tokenMap.put("userName", RESTNAME);
			String tokenMapJson = JSONUtil.toJSONString(tokenMap);

			Map<String, String> tokenAndCookiesByPost = getTokenAndCookiesByPost(OATOKEN_URL, tokenMapJson);
			log.info("客开日志-----------【cap4FormToPdf】tokenAndCookiesByPost: " + tokenAndCookiesByPost);
			String token = "";
			String cookie = "";
			token = MapUtils.getString(tokenAndCookiesByPost, "token");
			cookie = MapUtils.getString(tokenAndCookiesByPost, "Cookie");
			Map<String, Object> headers = new HashMap<String, Object>();


			headers.put("token", token);
			headers.put("Cookie", cookie);
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("affairId", affair.getId());
			bodyContent = HttpKit.post(OAIP + "/seeyon/rest/capImg/getHtmlStr", headers, jsonObject.toString());
			log.info("客开日志-----------【cap4FormToPdf】bodyContent: " + bodyContent);

			// ----------------------------------------------------------转pdf
			StringBuffer formContent = new StringBuffer(
					"<html> <head>  <meta charset=\"UTF-8\">  <title>表单</title> </head> <body style=\"text-align:center;\">");
			formContent.append(bodyContent);
			String formHtml = "";

			//添加意见
			//String yjFile = FileUpHelp.getComment(summaryId);// 把公文单文件先导出来
			//formContent.append(yjFile);

			formContent.append("</body></html>");
			formHtml += formContent.toString();
			String htmlTempFolder = ARCHIVE_TEMP_FOLDER;
			String htmlpath = htmlTempFolder + File.separator;
			File htmlFile = new File(htmlpath + summaryId + ".html");
			log.info("htmlpath：：：：" + htmlpath + summaryId +  ".html");
			if (!htmlFile.getParentFile().exists()) {
				htmlFile.getParentFile().mkdirs();
			}
			if (!htmlFile.exists()) {
				htmlFile.createNewFile();
			}
			OutputStream fileOutputStream = null;
			fileOutputStream = new FileOutputStream(htmlFile);
			fileOutputStream.write(formHtml.getBytes("utf-8"));
			if (fileOutputStream != null) {
				fileOutputStream.close();
			}
			String html = readFile(htmlpath + summaryId + ".html", "UTF-8");
			//doConversion2(html, htmlpath + summaryId + ".pdf");// pdf命名
			String filePath = htmlpath + summaryId + ".pdf";//表单-pdf
			log.info("KK:PDF文件路径：：：：" + filePath);
			return filePath;
			// ----------------------------------------------------------转pdf

		} catch (Exception e) {
			log.error("文单转png异常:", e);
		}


		return pdfURL;
	}

	/**
	 * 调用post接口获取token和cookies
	 * */
	public static Map<String,String> getTokenAndCookiesByPost(String address, String body) throws IOException {
		Map<String,String> mapResult = new HashMap<String,String>();

		CloseableHttpResponse response = null;
		CloseableHttpClient httpclient = null;
		CookieStore cookieStore  = new BasicCookieStore();
		try {
			httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
			HttpPost httpPost = new HttpPost(address);
			httpPost.setHeader("Content-Type", "application/json");
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectionRequestTimeout(120000)
					.setConnectTimeout(120000)
					.setSocketTimeout(120000)
					.build();
			httpPost.setConfig(requestConfig);
			StringEntity postingString = new StringEntity(body, "utf-8");
			httpPost.setEntity(postingString);
			response = httpclient.execute(httpPost);
			String tokenJson = EntityUtils.toString(response.getEntity(), "utf-8");
			//获取token信息
			if(tokenJson != null && tokenJson.contains("id")){
				Map map = JSONUtil.parseJSONString(tokenJson, Map.class);
				mapResult.put("token",map.get("id")+"");
			}else{
				mapResult.put("token",tokenJson);
			}

			//获取cookies
			//List<Cookie> cookies = cookieStore.getCookies();
			List<Cookie> cookies = cookieStore.getCookies();
			String Cookie = "";
			for(Cookie cookie:cookies){
				String name = cookie.getName();
				String value = cookie.getValue();
				Cookie = Cookie+name+"="+value+";";
			}
			mapResult.put("Cookie",Cookie);

			return mapResult;
		} finally {
			if (httpclient != null) {
				httpclient.close();
			}
			if (response != null) {
				response.close();
			}
		}
	}


	public final static String readFile(String path, String encoding) throws IOException {
		File f = new File(path);
		FileInputStream is = new FileInputStream(f);
		BufferedInputStream bis = new BufferedInputStream(is);
		ByteArrayOutputStream fos = new ByteArrayOutputStream();
		byte buffer[] = new byte[2048];
		int read;
		do {
			read = is.read(buffer, 0, buffer.length);
			if (read > 0) {
				fos.write(buffer, 0, read);
			}
		} while (read > -1);
		fos.close();
		bis.close();
		is.close();
		return fos.toString(encoding);
	}

	//public static void doConversion2(String htmlDocument, String outputPath) throws Exception { //抛出异常过多，建议直接抛最大异常
	//	log.info("jinlaile");
	//	PD4ML pd4ml = new PD4ML();
	//	pd4ml.enableDebugInfo();
	//	pd4ml.setHtmlWidth(userSpaceWidth);
	//	pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));
	//	pd4ml.setPageInsetsMM(new Insets(topValue, leftValue, bottomValue, rightValue));
	//	String classPath = FormToPdf.class.getResource("/") + "fonts";
	//	pd4ml.useTTF(classPath, true);
	//	pd4ml.setDefaultTTFs("simsun", "simsun", "simsun");
	//	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	//	pd4ml.render(new StringReader(htmlDocument), baos);
	//	baos.close();
	//	File output = new File(outputPath);
	//	java.io.FileOutputStream fos = new java.io.FileOutputStream(output);
	//	fos.write(baos.toByteArray());
	//	fos.close();
	//}
}